package service

import (
	"errors"
	"gin-bms/global"
	"gin-bms/model"
	"gin-bms/model/request"
	"gin-bms/utils"

	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

//用户注册
func Register(u model.SysUser) (err error, userOut model.SysUser) {
	var user model.SysUser
	if !errors.Is(global.GLOBAL_DB.Where("username=?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) {
		return errors.New("用户已注册"), userOut
	}
	u.Password = utils.MD5V([]byte(u.Password))
	u.UUID = uuid.NewV4()
	err = global.GLOBAL_DB.Create(&u).Error
	return err, u
}

//用户登录
func Login(u *model.SysUser) (err error, userOut *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.GLOBAL_DB.Where("username=? AND password=?", u.Username, u.Password).Preload("Role").First(&user).Error
	return err, &user
}

//修改密码
func ChangePassword(u *model.SysUser, newPassword string) (err error, userOut *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.GLOBAL_DB.Where("username=? AND password=?", u.Username, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
	return err, u
}

//更新用户
func UpdateUser(u model.SysUser) (err error, userOut model.SysUser) {
	err = global.GLOBAL_DB.Updates(&u).Error
	return err, u
}

//设置用户角色
func UpdateUserRole(uuid uuid.UUID, roleId string) (err error) {
	var user model.SysUser
	err = global.GLOBAL_DB.Where("uuid=?", uuid).First(&user).Update("role_id", roleId).Error
	return err
}

//删除用户
func DeleteUser(id float64) (err error) {
	var user model.SysUser
	err = global.GLOBAL_DB.Where("id=?", id).Delete(&user).Error
	return err
}

//分页获取用户数据
func GetUserInfoList(info request.PageInfo) (err error, userOutList interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GLOBAL_DB.Model(&model.SysUser{})
	var userList []model.SysUser
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Preload("role").Find(&userList).Error
	return err, userList, total
}

//通过id获取用户
func GetUserById(id float64) (err error, userOut *model.SysUser) {
	var user model.SysUser
	err = global.GLOBAL_DB.Where("id=?", id).First(&user).Error
	return err, &user
}

//通过uuid获取用户信息
func GetUserByUuid(uuid string) (err error, userOut *model.SysUser) {
	var user model.SysUser
	if err = global.GLOBAL_DB.Where("uuid=?", uuid).First(&user).Error; err != nil {
		return errors.New("用户不存在"), &user
	}
	return nil, &user
}
